package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomerException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional //事务，要么同时成功要么一起失败
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishService setmealDishService;

    //分页查询
    @Override
    public Page<SetmealDto> pageSetmealDto(Integer page, Integer pageSize, String name) {
        Page<SetmealDto> page1 = new Page(page, pageSize);
        Page<SetmealDto> page2 = setmealMapper.pageSetmealDto(page1, name);
        return page2;
    }

    //添加
    @Override
    public void addSetMealDto(SetmealDto setmealDto) {
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        //保存
        setmealDishService.saveBatch(setmealDishes);
    }

    //批量删除
    @Override
    public void deleteByIds(List<Long> ids) {
        //查询套餐状态如果有正在售卖的餐品，取消删除
        Integer count = this.lambdaQuery().in(Setmeal::getId, ids)
                .eq(Setmeal::getStatus, 1)
                .count();
        if (count > 0) {
            throw new CustomerException("有套餐正在售卖，无法删除");
        }
        //先删setmeal表
        this.removeByIds(ids);
        //再根据setmeal表的id删除setmeal_dish表
        setmealDishService.lambdaUpdate().in(SetmealDish::getSetmealId, ids).remove();
    }
    //根据id查询回显数据
    @Override
    public SetmealDto selectWithDish(Long id) {
        return setmealMapper.find(id);
    }
    //修改套餐
    @Override
    public void updateWithDish(SetmealDto setmealDto1) {
        this.updateById(setmealDto1);
        //先删除原来关联的数据，然后再添加
        setmealDishService.lambdaUpdate()
                .eq(SetmealDish::getSetmealId,setmealDto1.getId())
                .remove();
        //添加,并且为setmeal_dish设置套餐id
        List<SetmealDish> setmealDishes = setmealDto1.getSetmealDishes();
        setmealDishes.forEach(s->s.setSetmealId(setmealDto1.getId()));
        setmealDishService.saveBatch(setmealDishes);
    }
}
